package com.example.boom;

import static android.media.AudioManager.ADJUST_LOWER;
import static android.media.AudioManager.ADJUST_RAISE;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.example.boom.model.Instruction;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    // 自定义广播通知 用于通讯
    private MyBroadcastReceiver myBroadcastReceiver;
    private MediaPlayer player;

    private TextView curMusicTv;
    private TextView volumeNumTv;
    private TextView repeatNumTv;
    private TextView logTv;
    private Button playBtn;

    private List<String> musicList;     // 音乐列表
    private int curMusicIndex;          // 当前播放音乐index
    private int repeatNum;              // 重复次数

    private AudioManager audioManager;
    private SmsManager smsManager;

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 媒体
        player = new MediaPlayer();
        player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                onComplete();
            }
        });
        audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        smsManager = SmsManager.getDefault();

        // 组件绑定
        curMusicTv = findViewById(R.id.cur_music);
        volumeNumTv = findViewById(R.id.volume_num);
        repeatNumTv = findViewById(R.id.repeat_num);
        logTv = findViewById(R.id.log_tv);
        Button preBtn = findViewById(R.id.pre_btn);
        Button nextBtn = findViewById(R.id.next_btn);
        playBtn = findViewById(R.id.ply_btn);
        ListView listView = findViewById(R.id.lv);

        preBtn.setOnClickListener(v -> prePlay());
        nextBtn.setOnClickListener(v -> nextPlay());
        playBtn.setOnClickListener(v -> {
            if (player.isPlaying()) {
                pause();
                playBtn.setText("播放");
            } else {
                goPlay();
                playBtn.setText("暂停");
            }
        });

        // 音量调节
        volumeNumTv.setText("当前音量" + audioManager.getStreamVolume(AudioManager.STREAM_MUSIC));
        logTv.setText("当前系统最大音量: " + audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC) + "\n指令接收日志:\n");
        findViewById(R.id.volume_asc).setOnClickListener(v -> {
            audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, ADJUST_RAISE, 0);
            // 当前音量
            int streamVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
            volumeNumTv.setText("当前音量" + streamVolume);
        });
        findViewById(R.id.volume_desc).setOnClickListener(v -> {
            audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, ADJUST_LOWER, 0);
            // 当前音量
            int streamVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
            volumeNumTv.setText("当前音量" + streamVolume);
        });

        findViewById(R.id.test_btn).setOnClickListener(v -> {
             EditText viewById = findViewById(R.id.cmd_str);
             handleInstruction(new Instruction(viewById.getText().toString()));
             saveLog("调试指令: "+viewById.getText().toString());
        });

        // 音乐资源初始化
        try {
            musicList = getMusicList();
            if (musicList.size() == 0) {
                return;
            }
            curMusicIndex = 0;
            curMusicTv.setText("当前播放: " + musicList.get(curMusicIndex));
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
        listView.setOnItemClickListener((parent, view, position, id) -> {
            curMusicIndex = position;
            play();
        });
        //适配器初始化
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, musicList);
        //将适配器设置到ListView上
        listView.setAdapter(adapter);

        // 短信通讯
        myBroadcastReceiver = new MyBroadcastReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("ReadSMS");
        registerReceiver(myBroadcastReceiver, filter);

        // 资源准备完毕 按钮可点击
        preBtn.setEnabled(true);
        nextBtn.setEnabled(true);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(myBroadcastReceiver);
    }

    private class MyBroadcastReceiver extends BroadcastReceiver {
        @SuppressLint("SetTextI18n")
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("ReadSMS")) {
                System.out.println("收到广播!");
                String phone = intent.getStringExtra("phone");
                String message = intent.getStringExtra("instruction");
                // 解析指令
                Instruction inst = new Instruction(message);
                handleInstruction(inst);
                // 记录日志
                saveLog("收到 " + phone + " 的短信指令 :\n" + message);
                // 回显状态
                sendMessage(phone, getStatus());
            }
        }
    }

    // 获取音频资源列表
    public List<String> getMusicList() throws IOException {
        // 读取音乐列表
        String[] fileList = this.getAssets().list("");
        List<String> musicList = new ArrayList<>();
        for (String s : fileList) {
            if (s.contains(".mp3")) {
                musicList.add(s);
            }
        }
        return musicList;
    }

    // 播放指定音乐
    @SuppressLint("SetTextI18n")
    public void play() {
        try {
            player.reset();
            player.setDataSource(this.getAssets().openFd(musicList.get(curMusicIndex)));
            player.prepare();
            player.start();
            curMusicTv.setText("当前播放: " + musicList.get(curMusicIndex));
            playBtn.setEnabled(true);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 暂停
    public void pause() {
        if (player.isPlaying()) {
            player.pause();
        }
    }

    // 继续播放
    public void goPlay() {
        if (!player.isPlaying()) {
            player.seekTo(player.getCurrentPosition());
            player.start();
        }
    }

    // 上一首
    public void prePlay() {
        curMusicIndex--;
        if (curMusicIndex < 0) {
            curMusicIndex = musicList.size() - 1;
        }
        play();
    }

    // 下一首
    public void nextPlay() {
        curMusicIndex++;
        if (curMusicIndex > musicList.size() - 1) {
            curMusicIndex = 0;
        }
        play();
    }

    // 播放完成
    @SuppressLint("SetTextI18n")
    public void onComplete() {
        if (repeatNum <= 0) {
            return;
        }
        repeatNum--;
        repeatNumTv.setText("重复: " + repeatNum);
        if (repeatNum > 0) {
            play();
        }
    }

    // 设置音量
    @SuppressLint("SetTextI18n")
    public void setVolume(int number) {
        int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        if (number > maxVolume) {
            number = maxVolume;
        }
        if (number < 0) {
            number = 0;
        }

        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, number, 0);
        // 当前音量
        int streamVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        volumeNumTv.setText("当前音量" + streamVolume);
    }

    @SuppressLint("SetTextI18n")
    public void handleInstruction(Instruction inst) {
        // 记录日志
        if (inst.isStatusCMD()) {
            // 发送短信 函数执行结束后 统一回显当前状态
            return;
        }
        if (inst.isPlayCMD() && !player.isPlaying()) {
            playBtn.callOnClick();
            return;
        }
        if (inst.isStopCMD() && player.isPlaying()) {
            playBtn.callOnClick();
            return;
        }
        if (inst.getMusicName() != null) {
            for (int i = musicList.size() - 1; i >= 0; i--) {
                if (musicList.get(i).equals(inst.getMusicName())) {
                    curMusicIndex = i;
                    // 播放
                    play();
                    break;
                }
            }
        }
        if (inst.getVolume() != -1) {
            setVolume(inst.getVolume());
        }
        if (inst.getNum() != -1) {
            repeatNum = inst.getNum();
            repeatNumTv.setText("重复: " + repeatNum);
        }
    }

    public String getStatus() {
        StringBuilder builder = new StringBuilder();
        builder.append("当前状态: ");
        if (player.isPlaying()) {
            builder.append("播放中\n");
        } else {
            builder.append("已暂停\n");
        }
        builder.append("当前音频: ").append(musicList.get(curMusicIndex)).append("\n");
        builder.append("音量: ").append(audioManager.getStreamVolume(AudioManager.STREAM_MUSIC)).append("\n");
        builder.append("剩余重复次数: ").append(repeatNum).append(" 次");
        return builder.toString();
    }

    public void sendMessage(String phoneNumber, String message) {
        ArrayList<String> msgs = smsManager.divideMessage(message);
        for (String msg : msgs) {
            // 暂时忽略成功失败
            smsManager.sendTextMessage(phoneNumber, null, msg, null, null);
            saveLog("发送回显信息至" + phoneNumber);
        }
    }

    @SuppressLint("SetTextI18n")
    private void saveLog(String message) {
        @SuppressLint("SimpleDateFormat")
        SimpleDateFormat formatter= new SimpleDateFormat("[yyyy-MM-dd HH:mm:ss] ");
        Date date = new Date(System.currentTimeMillis());
        logTv.setText(logTv.getText() + formatter.format(date) + message + "\n");
    }
}